package LeetCode;

public class AddBinary {
  
  //Working!!!!
  public static String addBinary1(String a, String b) {
    // Start typing your Java solution below
    // DO NOT write main() function
    String result = "";
    int alen = a.length();
    int blen = b.length();
    
    int n = Math.min(alen, blen);
    
    int reside = 0;
    int plus = 0;
    for(int i = 1; i <= n; i++){
      int aInt = a.charAt(alen - i) - '0';
      int bInt = b.charAt(blen - i) - '0';
      int sum = aInt+bInt+plus;
      switch(sum){
      case 0: reside = 0; plus = 0; break;
      case 1: reside = 1; plus = 0; break;
      case 2: reside = 0; plus = 1; break;
      case 3: reside = 1; plus = 1; break;
      }
      result = reside+result;
    }
    
    if(n == alen){
      for(int i = n+1; i <= blen; i++){
        int bInt = b.charAt(blen - i) - '0';
        int sum = bInt+plus;
        switch(sum){
        case 0: reside = 0; plus = 0; break;
        case 1: reside = 1; plus = 0; break;
        case 2: reside = 0; plus = 1; break;
        case 3: reside = 1; plus = 1; break;
        }
        result = reside+result;
      }
    }else if(n == blen){
      for(int i = n+1; i <= alen; i++){
        int aInt = a.charAt(alen - i) - '0';
        int sum = aInt+plus;
        switch(sum){
        case 0: reside = 0; plus = 0; break;
        case 1: reside = 1; plus = 0; break;
        case 2: reside = 0; plus = 1; break;
        case 3: reside = 1; plus = 1; break;
        }
        result = reside+result;
      }
    }
    if(plus == 1)
      result=plus+result;
    return result;
  }
  
  //pass both, myself
  public String addBinary(String a, String b) {
    // Start typing your Java solution below
    // DO NOT write main() function
    StringBuilder sb = new StringBuilder();
    int ai = a.length() -1;
    int bi = b.length() -1;
    int carry = 0;
    while(ai >= 0 || bi >= 0){
        int sum = carry;
        if(ai >= 0) {
            sum += a.charAt(ai) - '0';
            ai--;
        }
        if(bi >= 0) {
            sum += b.charAt(bi) - '0';
            bi--;
        }
        if(sum >= 2) {
            carry = 1;
            sum -= 2;
        } else
            carry = 0;
        sb.insert(0, sum);
    }
    if(carry > 0)
        sb.insert(0, carry);
    return sb.toString();
}
  
  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(addBinary1("11", "1"));
  }

}
